<% content_for (:head)  do %>
    <title>Noisetube | Query</title>

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing,places&sensor=true"></script>
    <%=  javascript_include_tag "jquery.timeago" %>
    <%= javascript_include_tag "distgeo" %>

    <script type="text/javascript">

        //the map
        var map;
        var infowindow;
        var markers = [];
        var MAX_DISTANCE = 6;
        var MIN_ZOOM_LEVEL = 7;
        var MAX_ZOOM_LEVEL = 17;
        //google maps recommends array for all overlays
        var overlays = [];

        $(document).ready(function() {
            infowindow = new google.maps.InfoWindow({content: "<div class = '.infowindow'><i>Loading...</i></div>"});
            /*$.getJSON('/ajax/allcities.json', function(data) {
                $( "#city" ).autocomplete({
                    source: data,
                    minLength: 3,
                    select: function( event, ui ) {
                        $("#thecity").val(ui.item.id);
                    }
                });
            });*/
            $('#starttime').datetimepicker();
            $('#endtime').datetimepicker();

            //set the btn clicked to store in theaction hidden field
            $(":submit").click(function () { $("#theaction").val(this.id); });

            //ajax
            //load the map's measures on click
            $("#queryform").submit(function(e) {
                //get the data as json
                data = $('#queryform').serialize();

                var task = $('#theaction').val();

                var brlat = $('#geobr').val();
                //show dialog for bbox validation
                if (!brlat){
                    $( "#dialog-message" ).dialog({
                        modal: true,
                        buttons: {
                            Ok: function() {
                                $( this ).dialog( "close" );
                            }
                        }
                    });
                    e.preventDefault();
                }

            });
            //load the map
            initializeMap('map_canvas');

            //for downloading larger files
            $(document).on("click", "a.fileDownloadSimpleRichExperience", function() {
                $.fileDownload($(this).attr('href'), {
                    preparingMessageHtml: "Please wait...",
                    failMessageHtml: "There was a problem generating the dowbload, please try again."
                });
                return false; //stops the click event which will trigger a normal file download
            });
        });

        /*
         *  function initializeMap - id is the id for the elm
         */
        function initializeMap(id) {

            var usrLat, usrLng;
            //default client location
            // Try W3C Geolocation
            if(navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position) {
                    var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                    usrLat = initialLocation.lat();
                    usrLng = initialLocation.lng();
                    //change map center
                    if (map) map.setCenter(initialLocation);
                }, function() {
                    console.info("User location not detected.");
                });
            }
            // Browser doesn't support Geolocation
            else {
                console.info("User location not detected. Browser does not support this feature.");
            }

            var mapOptions = {
                center: new google.maps.LatLng(usrLat || 50.8, usrLng || 4.34),
                zoom: MIN_ZOOM_LEVEL + 4,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            map = new google.maps.Map(document.getElementById(id),
                    mapOptions);
            //restrict zoom levels
            var opts = { minZoom: MIN_ZOOM_LEVEL, maxZoom: MAX_ZOOM_LEVEL };
            map.setOptions(opts);
            var drawingManager = new google.maps.drawing.DrawingManager({
                drawingMode: null,//google.maps.drawing.OverlayType.RECTANGLE,
                drawingControl: true,
                drawingControlOptions: {
                    position: google.maps.ControlPosition.TOP_CENTER,
                    drawingModes: [
                        //google.maps.drawing.OverlayType.MARKER,
                        google.maps.drawing.OverlayType.RECTANGLE
                    ]
                }
            });
            drawingManager.setMap(map);

            //search box
            var input = document.getElementById('searchbox');
            var searchBox = new google.maps.places.SearchBox(input);

            google.maps.event.addListener(searchBox, 'places_changed', function() {
                var places = searchBox.getPlaces();

                var bounds = new google.maps.LatLngBounds();
                for (var i = 0, place; place = places[i]; i++) {
                    bounds.extend(place.geometry.location);
                }

                map.fitBounds(bounds);
            });
             //after rectangle is drawn...
            google.maps.event.addDomListener(drawingManager, 'rectanglecomplete', function(rectangle) {
                //remove other overlays
                removeOverlays(overlays);

                //only one shape, disable controls
                drawingManager.setOptions({
                    drawingMode: null
                    //drawingControl: false
                });

                //editable, draggable
                rectangle.setOptions({editable: true, draggable: true});

                function setBounds(rectangle) {
                    //get the rectangle bounds, set to controls
                    var tlLng =  rectangle.getBounds().getNorthEast().lng();
                    var tlLat =  rectangle.getBounds().getSouthWest().lat();

                    //get the rectangle bounds, set to controls
                    var ne =  rectangle.getBounds().getNorthEast();
                    var sw =  rectangle.getBounds().getSouthWest();

                    var brLat =  rectangle.getBounds().getNorthEast().lat();
                    var brLng =  rectangle.getBounds().getSouthWest().lng();

                    //disable if distance on diagonal > 4.3 kms
                    var p1 = new LatLon(ne.lat(),ne.lng());
                    var p2 = new LatLon(sw.lat(),sw.lng());
                    var dist = p1.distanceTo(p2);
                    //get the bearing
                    var bearing = p1.bearingTo(p2);

                    console.log("distance of bounds: "+dist);
                    if (dist > MAX_DISTANCE){
                        var pMax = p1.destinationPoint(bearing, MAX_DISTANCE);
                        //create bounds for sw
                        rectangle.setBounds(new google.maps.LatLngBounds(new google.maps.LatLng(pMax.lat(), pMax.lon()), ne));
                        //rectangle.setBounds(new google.maps.LatLngBounds( new google.maps.LatLng(tlLat,pMax.lon()), new google.maps.LatLng(pMax.lat(), tlLng)) );
                    }
                    // if (dist) > 4.3
                    $('#geotl').val(tlLat.toFixed(7) + ", " +tlLng.toFixed(7));
                    $('#geobr').val(brLat.toFixed(7) + ", " + brLng.toFixed(7));
                }

                //set bounds after drawing
                setBounds(rectangle);

                //set bounds if resized
                google.maps.event.addListener(rectangle, "bounds_changed", function() {

                    setBounds(rectangle);

                });

                //add rectangle to array
                overlays.push(rectangle);
            });
        }

        //load aggregated map from json data
        function loadAggregatedMap(data){
            //coloring for the average values of the regions
            var noisecolor = function(n)
            {
                if (!n)
                    return '';

                n = Number(n);

                if (n<35)
                    return  '#72c117';
                if (n>=35 && n<40)
                    return  '#72c117';
                if (n>=40 && n<45)
                    return  '#72c117';
                if (n>=45 && n<50)
                    return  '#72c117';
                if (n>=50 && n<55)
                    return  '#72c117';
                if (n>=55 && n<60)
                    return  '#c6c605';
                if (n>=60 && n<65)
                    return  '#FCB061';
                if (n>=65 && n<70)
                    return  '#FC8107';
                if (n>=70 && n<75)
                    return  '#FC4D4D';
                if (n>=75 && n<80)
                    return  '#EC0102';
                if (n>80)
                    return  '#990000';
                return '#8BB381';
            };

            removeOverlays(overlays);

            var mapbounds = new google.maps.LatLngBounds();
            //each array entry has grid coords, measures and stats
            var idx = 1;
            data.forEach(function(item){
                var index = idx;
                if (item.count > 0){   //skips empty grids

                    //create the boxes as overlays
                    var points = [
                        new google.maps.LatLng(item.xmin, item.ymin),
                        new google.maps.LatLng(item.xmax, item.ymin),
                        new google.maps.LatLng(item.xmax, item.ymax),
                        new google.maps.LatLng(item.xmin, item.ymax)

                    ];

                    // create for extending bounds
                    var clatlng = new google.maps.LatLng(item.xmax, item.ymax);
                    // increase the bounds to take this point
                    mapbounds.extend (clatlng);

                    var poly = new google.maps.Polygon({
                        paths: points,
                        strokeColor: noisecolor(item.mean),
                        strokeOpacity: 0.5,
                        strokeWeight: 1,
                        fillColor: noisecolor(item.mean),	//"#FF0000",
                        fillOpacity: 0.35
                    });

                    // Add a listener for the click event
                    google.maps.event.addListener(poly, 'click', function(evt){
                        //add info window then add to map
                        var sectortag = "<h2><%= t 'cities.infowindow.sector' %></h2>";
                        var sumtag = "<b><%= t 'cities.infowindow.sum' %>: </b>";
                        var meantag = "<b><%= t 'cities.infowindow.mean_html' %>: </b>";
                        var variancetag = "<b><%= t 'cities.infowindow.variance' %>: </b>";
                        var stdevtag = "<b><%= t 'cities.infowindow.stdev' %>: </b>";
                        var counttag = "<b><%= t 'cities.infowindow.count' %>: </b>";
                        var mintag = "<b><%= t 'cities.infowindow.min_html' %>: </b>";
                        var maxtag = "<b><%= t 'cities.infowindow.max_html' %>: </b>";

                        var text = "";
                        text += "<div class='grid-infowindow'>";
                        text += "<h2><%= t 'cities.infowindow.sector' %> "+ index+"</h2>";

                        text += counttag + (item.count || "n/a") + "<br/>";

                        //text += sumtag + (item.sum || "n/a") + "<br/>";
                        text += meantag + (item.mean ? item.mean.toFixed(2) : "n/a") + "<br/>";
                        //text += variancetag + (item.variance || "n/a") + "<br/>";
                        text += stdevtag + (item.stdev ? item.stdev.toFixed(2) : "n/a")  + "<br/>";
                        text += mintag + (item.min || "n/a") + "<br/>";
                        text += maxtag + (item.max || "n/a") + "<br/>";

                        text += "</div>";

                        infowindow.setContent(text);
                        infowindow.setPosition(evt.latLng);
                        infowindow.open(map);
                    });

                    poly.setMap(map);
                    overlays.push(poly);
                    //increase index
                    idx += 1;
                }
            });

            if (data.length > 0) map.fitBounds(mapbounds);
        }

        function removeOverlays(overlays) {
           if (overlays && overlays.length > 0){
                //remove overlays
                while(overlays[0]){
                    overlays.pop().setMap(null);
                }
           }
        }
    </script>

<% end %>


<div id="page">
  <% if flash[:error] %>
      <div class="flash error">
       <p> <%= flash[:error] %> </p>
      </div>
  <% end %>
  <% if flash[:alert] %>
      <p><%= flash[:alert] %></p>
  <% end %>
  <% if flash[:notice] %>
      <div class="flash notice">
      <p><%= flash[:notice] %></p>
    </div>
  <% end %>
</div>

<div class="intro">
  <h3><%= t 'cities.iscope.aggmaps.title' %> </h3>
  <p><%=  t 'cities.iscope.aggmaps.desctwo' %></p>
</div>
<br/>

<h3>Map</h3>
<div id="map_canvas" style="width:90%; height:400px"></div>
<br />
<%= label_tag("searchbox", (t "cities.iscope.searchbox") << ": ") %>
<%= text_field_tag 'searchbox', nil, :placeholder=> (t 'cities.iscope.aggmaps.entername'), :class => 'form_text_field', :size => '90%' %>
<br/>
<hr />
<h3><%= t 'cities.headings.aggmaps.requestaggmap' %> </h3>
<div>
  <p>
    <%= form_tag "/cities/aggcitymeasures_delayed", id: "queryform"  do %>
        <!-- TODO: add validation - must select at least one user -->
        <%= label_tag("mapname", (t "cities.iscope.aggmaps.mapname") << ": ") %>
        <%= text_field_tag 'mapname', nil, :placeholder => (t 'cities.iscope.aggmaps.typemapname'), :class => 'form_text_field_latlng' %>
        <br /><br />
        <p ><%= t 'cities.iscope.aggmaps.timebetween' %></p>
        <%= label_tag("starttime", (t "cities.iscope.starttime")) %>
        <%= text_field_tag 'starttime', nil, :class => 'form_text_field'%>
        <br /><br />
        <%= label_tag("endtime", (t "cities.iscope.endtime")) %>
        <%= text_field_tag 'endtime', nil, :class => 'form_text_field'%>
        <br /><br />

        <input type="hidden" name="theaction" id="theaction" />
        <input type="hidden" name="thecity" id="thecity" />
        <input type="hidden" name="geotl" id="geotl" />
        <input type="hidden" name="geobr" id="geobr" />

        <div id="form-buttons">
          <%=  submit_tag (t "cities.iscope.aggmaps.queueaggmap"), {id: "btnaggmap"} %>
        </div>

    <% end %>
    </p>
</div>
<hr />
<h3><%= t 'cities.headings.aggmapsforcity' %></h3>

<div id="results" >

<%#*<div style="margin:5px">sorted by: date, average exposure, duration, geo coverage%>

  <center style="font-size:12px"> <%= will_paginate @aggmaps unless @aggmaps.blank?  %>  </center>
  <br/>
  <ul style=" align:left; overflow: auto; list-style: none inside; ">
    <%
       #distance_of_time_in_words(t.start, t.end)
       unless @aggmaps.blank?
       @aggmaps.each_with_index {|aggmap,i|
         if aggmap.generated
    %>
            <li style="background-color: rgb(235, 235, 235);padding-left:0px; margin-left:20px;margin-bottom:20px">

              <table  class="borderless" width="100%" border="0" cellpadding="0" cellspacing="0">
                <tbody>
                <tr>
                  <td width="15"><img src="/images/roundedcornr_348668_tl.png" alt="Rounded Corner: Top-left" border="0" height="15"/></td>
                  <td></td>
                  <td width="15"><img src="/images/roundedcornr_348668_tr.png" alt="Rounded Corner: Top-right" border="0" height="15"/></td>
                </tr>
                <tr>
                  <td></td>
                  <td>
                    <div class="header">
                      <div style="float:left">
                        <b>Name:</b> <font style="font-size: 11px;" color="#777777"><%= aggmap.name %></font><br/>
                        <b>Start time:</b> <font style="font-size: 11px;" color="#777777"><%= aggmap.start_time %></font><br/>
                        <b>End time:</b> <font style="font-size: 11px;" color="#777777"><%= aggmap.end_time %> (<%=distance_of_time_in_words(aggmap.end_time, Time.now) unless aggmap.end_time.nil? %> ago)</font><br /><br />

                        <b>Measurements: </b>
                          <font style="font-size: 11px;" color="#777777"> <br/>
                            Duration: <% if aggmap.try(:start_time) %>
                                <%=  distance_of_time_in_words(aggmap.end_time,aggmap.start_time)  %> <br/>
                            <% else %>
                                (unknown)
                            <% end %>
                            No. of Measurements: <%= aggmap.try(:measures_size) %> <br/>
                            Average: <%= aggmap.try(:meandb) %> dB(A)<br/>

                          </font>

                      </div>
                      <div style="float:right">
                        <a href="/cities/custommaps.json?id=<%=  aggmap.id %>"><img src="/images/icons/data-download.jpg" align="absmiddle" alt="Download data" style="width: 16px; height: 16px;"/>&nbsp;Data</a>
                        <%  if logged_in? && @user == current_user %>
                            &nbsp;&nbsp;
                            <!-- loading icon -->
                            <%=  image_tag("/images/icons/spinner.gif", :class => "loading-icon", :style => 'width: 12px; height: 12px;', :id=> "wait-#{aggmap.id}") %>

                            <a href="#" id="aggmap-<%= aggmap.id %>" >
                              <img src="/images/icons/markericon.png" align="absmiddle" alt="Load map" style="width: 16px; height:16px;"/>&nbsp;<%= t 'cities.links.showonmap' %>
                            </a>

                            <script type="text/javascript">
                                //load the map's measures on click
                                $('#aggmap-<%= aggmap.id %>').on('click', function(e) {
                                    //get the parent id
                                    var link_id = $(this).attr("id");

                                    //wait gif
                                    $('#wait-<%= aggmap.id %>').show();
                                    //$('#'+link_id).hide();
                                    $.get("/ajax/get_aggmap?id="+link_id, function(data) {
                                        $('#wait-<%= aggmap.id %>').hide();
                                       // $('#'+link_id).show();
                                        if (data && data !== "[]" && data !== ""){
                                            var dataJson = $.parseJSON(data);
                                            //load the map
                                            loadAggregatedMap(dataJson);
                                            //focus map
                                            $('html, body').animate({ scrollTop: $('#map_canvas').offset().top }, 'slow');
                                            //reset the text
                                            //$('#'+link_id).text("<%= t 'cities.links.shownonmap' %>")
                                        }
                                        else {
                                            $('#'+link_id).text("<%= (t 'cities.links.nomap') %>")
                                            console.log("Could not load the map. ");
                                        }
                                    });

                                    e.preventDefault();
                                    return false;
                                });
                            </script>
                        <% end%>
                      </div>

                    </div>
                    <br />  <br />


                    <div style="float:right;width:140px" >
                      <%  unless aggmap.bounds.nil? #nil check just to be sure
                           center=aggmap.bounds.envelope.centroid
                      %>
                          <img src="http://maps.google.com/staticmap?key=ABQIAAAAEDqSJ7sjOq1o3M9HFMUctBTP6FiD4Pq0_NOM64wEPpZs4eDxtRS5-gQAVDwr5RxsOtxOMbZGzM-pjQ&sensor=true&center=<%=center.lat%>,<%=center.lng%>&zoom=13&size=120x120" width="120"/><br/>
                          <a href="/cities/custommaps.kml?id=<%= aggmap.id %>"  class="fileDownloadSimpleRichExperience"><img src="/images/icons/KML_16x16.png" align="absmiddle" alt="KML" />&nbsp;Download kml</a><br />
                          <a href="/cities/custommaps.zip?id=<%= aggmap.id %>"  class="fileDownloadSimpleRichExperience"><img src="/images/icons/KML_16x16.png" align="absmiddle" alt="shpfile" />&nbsp;shapefile</a><br/>

                      <%  end %>
                    </div>

                  </td>
                  <td></td>
                </tr>
                <tr>
                  <td><img src="/images/roundedcornr_348668_bl.png" alt="" border="0" width="15" height="15"/></td>
                  <td></td>
                  <td><img src="/images/roundedcornr_348668_br.png" alt="" border="0" width="15" height="15"/></td>
                </tr>
                </tbody></table>
            </li>

        <%  else %>
            <li >
              <table cellpadding="5" cellspacing="0" style="background-color: rgb(240, 240, 240); width:100%; padding:5px">
                <tr><td>
                  <b>Name:</b><font style="font-size: 11px;" color="#777777"> <%= aggmap.name %> </font><br/>
                  <b>Start time:</b><font style="font-size: 11px;" color="#777777"> <%= aggmap.start_time %> </font><br/>
                  <b>End time:</b><font style="font-size: 11px;" color="#777777"> <%= aggmap.end_time %> (<%=distance_of_time_in_words(aggmap.end_time, Time.now) unless aggmap.start_time.nil? %> ago) </font><br/>
                  <p><center><b>
                  <%= t 'cities.iscope.aggmaps.mapnotprocessed'  %></b>
                </center></p>
                </td></tr>
              </table>
              <hr style="background-color:#FFFFFF"/>
            </li>
        <%  end %>


    <% }
     else
    %>
      <p><%=  t 'cities.headings.aggmaps.noaggmaps' %> </p>
     <%
     end
     %>
  </ul>


  <div id="dialog-message" title="<%= t 'cities.iscope.aggmaps.nomapdrawn' %>" style="display:none;">
    <br />
    <p>
      <span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 10px 0;"></span>
      <%= t 'cities.iscope.aggmaps.drawmapfirst' %>
    </p>
  </div>
</div>